//
//  MyselfViewController.m
//  HomeFinder
//
//  Created by 蒋永昌 on 16/2/25.
//  Copyright © 2016年 蒋永昌. All rights reserved.
//

#import "MyselfViewController.h"
#import "LoginViewController.h"
#import "SetupViewController.h"
#import "FeedbackViewController.h"

#import <Masonry.h>
#import <AVOSCloud/AVOSCloud.h>

@interface MyselfViewController ()<UITableViewDataSource,UITableViewDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate>

@property(nonatomic,strong)UITableView *myselfTableView;
@property(nonatomic,strong)NSMutableArray *dataArray;
@property(nonatomic,strong)UIButton *icon;
@property(nonatomic,strong)UILabel *loginLabel;
@property(nonatomic,strong)UIImage *iconImage;
@property(nonatomic,strong)AVUser *currentUser;

@end

@implementation MyselfViewController

-(void)viewWillAppear:(BOOL)animated{

    self.tabBarController.tabBar.hidden = NO;

    self.currentUser = [AVUser currentUser];
    if (self.currentUser != nil) {
        // 在线状态
        
        self.loginLabel.text = @"点击头像上传图片";

        AVFile *fileImageV = self.currentUser[@"Picture"];
        
            if (fileImageV != nil) {
                
                [fileImageV getDataInBackgroundWithBlock:^(NSData *data, NSError *error) {
                   
                    [self.icon setImage:[UIImage imageWithData:data] forState:UIControlStateNormal];
                }];
                
            }else{
                
                [self.icon setImage:[UIImage imageNamed:@"headHigh.jpg"] forState:UIControlStateNormal];

            }
            
//        }];

        

    } else {
        // 离线状态
        [self.icon setImage:[UIImage imageNamed:@"head.png"] forState:UIControlStateNormal];
        self.loginLabel.text = @"点击头像登录/注册";
    }

}


- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor grayColor];
    
    self.currentUser = [AVUser currentUser];
    
    self.navigationItem.title = @"我的";
    
    self.myselfTableView = [[UITableView alloc]initWithFrame:self.view.bounds style:UITableViewStyleGrouped];

    self.view = self.myselfTableView;
    
    self.myselfTableView.delegate = self;
    self.myselfTableView.dataSource = self;
    
    [self addHeaderView];
    
    [self makeModelSource];

}

-(void)addHeaderView{

    //背景图
    UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, 180)];
    headerView.backgroundColor = [UIColor colorWithRed:0.601 green:0.623 blue:0.554 alpha:1.000];
    headerView.userInteractionEnabled = YES;
   
    self.myselfTableView.tableHeaderView = headerView;

    
    //头像
    self.icon = [[UIButton alloc]init];
    [self.icon setImage:[UIImage imageNamed:@"head"] forState:UIControlStateNormal];
    self.icon.layer.masksToBounds = YES;
    self.icon.layer.cornerRadius = 35;
    [headerView addSubview:self.icon];
    
    [self.icon mas_makeConstraints:^(MASConstraintMaker *make) {
       
        make.size.mas_equalTo(CGSizeMake(70, 70));
        make.center.equalTo(headerView).centerOffset(CGPointMake(0, -20));
        
    }];
    
    
    //文字
    self.loginLabel = [[UILabel alloc]init];
    self.loginLabel.text = @"点击头像登录/注册";
    self.loginLabel.font = [UIFont systemFontOfSize:14];
    self.loginLabel.textAlignment = NSTextAlignmentCenter;
    
    [headerView addSubview:self.loginLabel];
    
    [self.loginLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.size.mas_equalTo(CGSizeMake(300, 20));
        make.center.equalTo(headerView).centerOffset(CGPointMake(0, 40));
        
        
    }];

    
    [self.icon addTarget:self action:@selector(loginAndRegisterAction:) forControlEvents:(UIControlEventTouchUpInside)];
    
    
}

//用户未登录时点击头像事件
-(void)loginAndRegisterAction:(UIButton*)sender{


    if (self.currentUser != nil) {
        
        self.loginLabel.text = @"点击头像上传图片";
  
        [self upLoadPicture];
        
    }else{
        
        self.loginLabel.text = @"点击头像登录/注册";
        
        LoginViewController *loginVC = [[LoginViewController alloc]init];
        
        [self.navigationController pushViewController:loginVC animated:YES];


    }
    



}

// 用户在线时点击头像上传头像
- (void)upLoadPicture{
    
    UIImagePickerController *imagePicker = [[UIImagePickerController alloc]init];
    
    imagePicker.delegate = self;
    imagePicker.allowsEditing = YES;
    
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
        [self presentViewController:imagePicker animated:YES completion:nil];
        
    }];
    
    UIAlertAction *action2 = [UIAlertAction actionWithTitle:@"本地" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        [self presentViewController:imagePicker animated:YES completion:nil];
        
    }];
    
    UIAlertAction *action3 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    
    [alert addAction:action1];
    [alert addAction:action2];
    [alert addAction:action3];
    
    [self presentViewController:alert animated:YES completion:nil];
    

    
}

// 相册代理方法
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
    
    self.iconImage = [UIImage imageNamed:@""];
    self.iconImage = [info objectForKey:UIImagePickerControllerOriginalImage];
    
    [self.icon setImage:self.iconImage forState:UIControlStateNormal];
    
    [self dismissViewControllerAnimated:YES completion:^{
        
        // 转化为二进制数据
        NSData *imageData = UIImageJPEGRepresentation(self.iconImage, .2f);
        AVFile *imageFile = [AVFile fileWithData:imageData];
        
        // 在线状态
        [self.currentUser setObject:imageFile forKey:@"Picture"];
        NSLog(@"用户在线");
        [self.currentUser signUpInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
            
            if (succeeded) {
                
                [imageFile getDataInBackgroundWithBlock:^(NSData *data, NSError *error) {
                    
                    [self.icon setImage:[UIImage imageWithData:data] forState:UIControlStateNormal];
                }];

                NSLog(@"上传成功%@",imageFile.objectId);
            }else{
                
                NSLog(@"上传失败:%@",error);
            }
            
        }];

        
    }];
    
}


//制作数据
-(void)makeModelSource{

    NSArray *sectionArray1 = [NSArray arrayWithObjects:@"我的订单",
                                                       @"我的收藏",
                                                       @"浏览历史",
                                                       @"我的消息", nil];
    
    NSArray *sectionArray2 = [NSArray arrayWithObjects:@"系统设置",
                                                       @"意见反馈", nil];
    
    NSArray *sectionArray3 = [NSArray arrayWithObjects:@"退出登录", nil];
    

    self.dataArray = [NSMutableArray array];
    
    [self.dataArray addObject:sectionArray1];
    [self.dataArray addObject:sectionArray2];
    [self.dataArray addObject:sectionArray3];

}





- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{

    return [self.dataArray count];


}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{

    return [self.dataArray[section] count];


}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    
    if (cell == nil) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
    }

    
    cell.textLabel.text = self.dataArray[indexPath.section][indexPath.row];
    
    
    //退出登录按钮为红色
    if (indexPath.section == 2) {
        
        cell.textLabel.textAlignment = NSTextAlignmentCenter;
        cell.textLabel.textColor = [UIColor colorWithRed:0.968 green:0.000 blue:0.009 alpha:1.000];
    }
    
    
    return cell;

}


-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{

    
    
    if (indexPath.section == 0) {
        
        LoginViewController *loginVC = [[LoginViewController alloc]init];
        
        [self.navigationController pushViewController:loginVC animated:YES];
    
    }
    
    //系统设置
    if (indexPath.section == 1) {
       
        if (indexPath.row == 0){
            
            SetupViewController *setupVC = [[SetupViewController alloc]init];
            
            [self.navigationController pushViewController:setupVC animated:YES];
        }else if (indexPath.row == 1){
        
            FeedbackViewController *feedVC = [[FeedbackViewController alloc]init];
            
            [self.navigationController pushViewController:feedVC animated:YES];
        
        }
        

        
    }
    
    if (indexPath.section == 2) {
        
        if (self.currentUser != nil) {
            
            UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"确定退出" message:nil preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                
                [AVUser logOut];  //清除缓存用户对象
                
                self.currentUser = nil;
                
                [self.icon setImage:[UIImage imageNamed:@"head.png"] forState:UIControlStateNormal];
                
                
            }];
            UIAlertAction *action2 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
            
            [alert addAction:action1];
            [alert addAction:action2];
            
            [self presentViewController:alert animated:YES completion:nil];

        }
        

    }

}


-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return 50;

}






- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
